<template>
  <div class="app-container">
    <!--单指标风险区划评估地图模块-->
    <Index :dataType="dataType" :form="queryForm" @openQueryDiv="openQueryDiv"></Index>
    <!--查询面板-->
    <div class="new-queryDiv" v-show="openBool" v-loading="loading">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="区划记录编号" prop="zoningCode">
              <el-input v-model="form.zoningCode" disabled style="width:293px;margin-right:10px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区划记录名称" prop="zoningName">
              <el-input v-model="form.zoningName" clearable style="width:293px;margin-right:10px;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="区划记录描述" prop="zoningDesc">
          <el-input v-model="form.zoningDesc" clearable style="width:293px;margin-right:10px;"></el-input>
        </el-form-item>
        <el-form-item label="评估对象" prop="estimateObj">
          <el-select v-model="form.estimateObj" placeholder="请选择" style="width: 300px;" @change="typeChange">
            <el-option key="seismicEd" label="抗震能力" value="1"></el-option>
            <el-option key="personCasualtiesEd" label="人员伤亡" value="2"></el-option>
            <el-option key="economicLossesEd" label="经济损失" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行政区划" prop="divisionNames">
          <AreaCascader @getAreaSelect="getAreaSelect" :divisionNames="form.divisionNames" style="width: 300px;z-index:10;" />
        </el-form-item>
        <el-form-item label="选择房屋基础数据" style="display:block;width: 100%;" prop="houseDataFlag">
          <el-radio-group v-model="form.houseDataFlag">
            <el-radio v-for="item in houseBasicData" :key="item.value" :label="item.value" size="large">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="地震输入方式" style="display:block;width: 100%;" prop="seismicInputMode">
          <el-radio-group v-model="form.seismicInputMode" @change="modeChange">
            <el-radio v-for="item in inputMethods('confirm')" :key="item.value" :label="item.value" size="large">
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row v-if="form.seismicInputMode == 0">
          <el-col :span="9">
            <el-form-item label="烈度" prop="condition" v-if="form.seismicInputMode == 0">
              <el-select v-model="form.condition" placeholder="请选择" style="width: 100%;">
                <el-option v-for="item in dictData.intensity" :key="item.dictItemId" :label="item.dictItemName"
                           :value="item.dictItemCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="时间段" prop="timeRange" v-if="form.estimateObj=='2'" label-width="80px">
              <el-select v-model="form.timeRange" placeholder="请选择" style="width: 100%;" disabled>
                <el-option v-for="item in dictData.sjd" :key="item.dictItemId" :label="item.dictItemName"
                           :value="item.dictItemCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重伤/死亡" prop="casualtyType" v-if="form.estimateObj=='2'" label-width="100px">
              <el-select v-model="form.casualtyType" placeholder="请选择" style="width: 100%;" disabled>
                <el-option v-for="item in dictData.rysw" :key="item.dictItemId" :label="item.dictItemName"
                           :value="item.dictItemCode" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col :span="24">
            <el-form-item label="超越概率" prop="condition" v-if="form.seismicInputMode == 1">
              <el-select v-model="form.condition">
                <el-option v-for="item in dictData.probability" :key="item.dictItemId" :label="item.dictItemName"
                           :value="item.dictItemCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="condition" v-if="form.seismicInputMode == 2">
              <el-button plain @click="chooseInfluenceField">选择影响场数据</el-button>
              <el-input v-model="form.condition" style="width: 300px;" v-show="form.condition"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="评估记录编号" prop="assessCodes">
          <el-input v-model="form.assessCodes" clearable disabled style="width:293px;margin-right:10px;"></el-input>
          <el-button type="primary" @click="openDialog=true">选择评估记录数据</el-button>
        </el-form-item>
        <hr style="margin-bottom: 20px;">
        <div style="text-align:right;">
          <el-button type="primary" @click="handleQuery">区划</el-button>
        </div>
      </el-form>
    </div>

    <!--选择评估记录-->
    <el-dialog v-model="openDialog" title="选择评估记录" width="1000px" append-to-body @close="openDialog=false">
      <div style="padding:20px;">
        <AssessList v-if="openDialog"
                    :estimateObj="form.estimateObj" :houseDataFlag="form.houseDataFlag" :seismicInputMode="form.seismicInputMode"
                    :type="TYPE.confirm" @getSelectData="getSelectData"
        ></AssessList>
      </div>
    </el-dialog>
    <!--选择地震影响场-->
    <InfluenceField v-model:open="influenceFieldOpen" :selected="form.condition" @getInfluence="getInfluence" />
  </div>
</template>

<script setup name="singleRiskZonationConfirmMap">
//地图
import Index from '@/map/buildingRiskZoning/singleRiskZonation/index.vue';
import AssessList from '@/views/buildingRiskZoning/singleRiskZonation/components/assessList.vue'
import AreaCascader from '@/views/buildingRiskZoning/singleRiskZonation/components/areaCascader.vue'
import InfluenceField from '@/views/building/components/influenceField.vue'
import { TYPE, URL, inputMethods, houseBasicData } from '@/views/building/index'
import { getDict } from '@/api/system/dict.js'
import { getSingle } from '@/api/buildingRiskZoning/standardSetting/index'
import { getProvince, getChildArea } from "@/api/system/division"
import { getById,getZoningCode,doZoning } from '@/api/buildingRiskZoning/singleRiskZonation/index'

const { proxy } = getCurrentInstance();
const route = useRoute();
//单指标风险区划-确定评估风险区划
const dataType = ref("singleRiskZonationConfirm");//单指标风险区划-确定评估风险区划
const data = reactive({
  queryForm:{
    assessType:"seismicEd",
    range:{},//四个临界值设置;新疆、青海和西藏地区四个临界值设置
    faeId: "", //id
  },
  form:{
    faeId: "", //id
    zoningCode: "", //区划记录编码
    zoningName: "", //区划记录名称
    zoningDesc: "", //区划记录描述
    estimateObj: "1", //评估对象 1、抗震能力；2、人员伤亡；3、经济损失
    divisionNames: "", //行政区划
    houseDataFlag: "0", //选择房屋基础数据 0、房屋单体数据；1、房屋网格数据
    seismicInputMode: "0",//地震输入方式 0、烈度；1、4个概率水准；2、地震影响场
    assessCodes:"", //评估记录编号
    condition: "ld1", //烈度时（ld1，ld2，ld3，ld4，ld5）；地震影响场时（影响场版本）；4个概率水准时（sgglsz1、sgglsz2、sgglsz3、sgglsz4）
    conditionType: "11", //11:烈度;21:4个概率水准(ld);22:4个概率水准(pga);31:地震影响场
    timeRange:"sjd2",//夜间
    casualtyType:"rysw2",//死亡
    range:{},//四个临界值设置;新疆、青海和西藏地区四个临界值设置
  },
  rules:{
    zoningCode: [{ required: true, message: "区划记录编码不能为空", trigger: "change" }],
    zoningName: [{ required: true, message: "区划记录名称不能为空", trigger: "change" }],
    estimateObj: [{ required: true, message: "评估对象不能为空", trigger: "change" }],
    divisionNames: [{ required: true, message: "行政区划不能为空", trigger: "change" }],
    houseDataFlag: [{ required: true, message: "选择房屋基础数据不能为空", trigger: "change" }],
    seismicInputMode: [{ required: true, message: "地震输入方式不能为空", trigger: "change" }],
    assessCodes: [{ required: true, message: "评估记录编号不能为空", trigger: "change" }],
    condition: [{ required: true, message: "不能为空", trigger: "change" }],
    range: [{ required: true, message: "请先设置单指标风险区划设置", trigger: "change" }],
  },
  resultQhList:[],//区划结果列表
  resultEntity:[],//区划结果数据
  rangeObj:{},//四个临界值设置;新疆、青海和西藏地区四个临界值设置
})
const { queryForm,form,rules,resultQhList,resultEntity,rangeObj } = toRefs(data)

const loading = ref(false);
const openBool = ref(true);
const openQueryDiv = (bool) => {
  openBool.value = bool;
}

//获取选择的行政区划列表
const getAreaSelect = (obj) =>{
  console.log("getAreaSelect");
  if(obj){
    console.log("获取选择的行政区划列表");
    console.log(obj);
    form.value.divisionNames = obj.divisionNames;
    console.log(form.value);
  }
}

// 字典项
const dictData = ref({
  intensity: [],//烈度
  probability: [],//超越概率
  phcd:[],//破坏程度
  sjd:[],//时间段
  rysw:[],//重伤/死亡
});

// 字典项
const getDictData = (field, code) => {
  getDict(code).then(res => {
    dictData.value[field] = res.data
    console.log("字典项"+field+","+code)
    console.log(res.data)
  })
}

//初始化
const initOpen = () => {
  getDictData('intensity', 'ld')
  getDictData('probability', 'sgglsz')
  // getDictData('phcd', 'pgcd')
  getDictData('rysw', 'rysw')
  getDictData('sjd', 'sjd')
  console.log(route);
  let id = route.query.id;
  console.log("id"+id);
  if(id){//已有区划记录
    //根据id获取区划记录信息
    getDataById(id);
  }else{//新建
    //获取区划记录编号
    getZoningCode().then(res => {
      if (res.code == 200) {
        form.value.zoningCode = res.data
      }
    })
  }
}

const form1 = ref({});//抗震能力/极限状态四个临界值设置
const form2 = ref({});//死亡人数四个临界值设置
const form3 = ref({});//直接经济损失/区域内上年度 GDP四个临界值设置
//根据类型查询四个临界值设置
const getData = (type) => {
  getSingle({ type }).then(res => {
    if (res.code == 200) {
      if (type == '1') {
        form1.value = res.data
      } else if (type == '2') {
        form2.value = res.data
      } else {
        form3.value = res.data
      }
    }
  })
}

//选择评估对象--获取单指标风险区划临界值
const typeChange = (estimateObj) =>{
  let range = {};
  if(estimateObj=="1"){
    range = form1.value;
  }else if(estimateObj=="2"){
    range = form2.value;
  }else if(estimateObj=="3"){
    range = form3.value;
  }
  form.value.range = range;
  rangeObj.value = range;
  console.log("range");
  console.log(range);
}

//选择评估记录
const openDialog = ref(false);
const selectData = ref([]);
const getSelectData = (data) => {
  selectData.value = data;
  let str = "";
  if(data){
    for(let i=0;i<data.length;i++){
      if(i>0){
        str += ",";
      }
      str += data[i].assessCode;
    }
  }
  form.value.assessList = data;
  form.value.assessCodes = str;
  openDialog.value = false;
}

//区划结果查询
const handleQuery = () => {
  queryForm.value = {};//清空
  proxy.$refs["ruleForm"].validate(valid => {
    if (valid) {
      loading.value = true;
      //区划计算
      doZoning({...form.value}).then(res => {
        console.log(res);
        if (res.code == 200) {
          console.log("区划结果查询")
          console.log(form.value)
          console.log(form1.value)
          console.log(form2.value)
          console.log(form3.value)
          //选择评估对象--获取单指标风险区划临界值
          typeChange(form.value.estimateObj);
          let list = res.data;
          let faeId = "";
          if(list!=null && list.length>0){
            faeId = list[0].faeId;
          }
          form.value.faeId = faeId;
          let assessType = "seismicEd";
          let estimateObj = form.value.estimateObj;//评估对象 1、抗震能力；2、人员伤亡；3、经济损失
          if(estimateObj=="1"){
            assessType = "seismicEd";
          }else if(estimateObj=="2"){
            assessType = "personCasualtiesEd";
          }else if(estimateObj=="3"){
            assessType = "economicLossesEd";
          }
          //区划查询
          queryForm.value = {
            assessType:assessType,
            range:rangeObj.value,//四个临界值设置;新疆、青海和西藏地区四个临界值设置
            faeId: faeId, //id
          };
          proxy.$modal.msgSuccess('计算成功！')
          loading.value = false;
          openBool.value = false;
        }
      }).catch(err => {
        loading.value = false;
      });
    }
  });
}

//根据id获取区划记录信息
const getDataById = (id)=>{
  loading.value = true;
  getById(id).then(res => {
    if (res.code == 200) {
      loading.value = false
      resultQhList.value = res.data.list;
      resultEntity.value = res.data.entity;
      form.value = {
        faeId: resultEntity.value.faeId, //id
        zoningCode: resultEntity.value.zoningCode, //区划记录编码
        zoningName: resultEntity.value.zoningName, //区划记录名称
        zoningDesc: resultEntity.value.zoningDesc, //区划记录描述
        estimateObj: resultEntity.value.estimateObj, //评估对象 1、抗震能力；2、人员伤亡；3、经济损失
        divisionNames: resultEntity.value.divisionNames, //行政区划
        houseDataFlag: resultEntity.value.houseDataFlag, //选择房屋基础数据 0、房屋单体数据；1、房屋网格数据
        seismicInputMode: resultEntity.value.seismicInputMode,//地震输入方式 0、烈度；1、4个概率水准；2、地震影响场
        assessCodes:resultEntity.value.assessCodes, //评估记录编号
        condition: resultEntity.value.condition, //烈度时（ld1，ld2，ld3，ld4，ld5）；地震影响场时（影响场版本）；4个概率水准时（sgglsz1、sgglsz2、sgglsz3、sgglsz4）
        conditionType: resultEntity.value.conditionType, //11:烈度;21:4个概率水准(ld);22:4个概率水准(pga);31:地震影响场
        timeRange:"sjd2",//夜间
        casualtyType:"rysw2",//死亡
        range:rangeObj.value,//四个临界值设置;新疆、青海和西藏地区四个临界值设置
      };
      let assessType = "seismicEd";
      let estimateObj = form.value.estimateObj;//评估对象 1、抗震能力；2、人员伤亡；3、经济损失
      if(estimateObj=="1"){
        assessType = "seismicEd";
      }else if(estimateObj=="2"){
        assessType = "personCasualtiesEd";
      }else if(estimateObj=="3"){
        assessType = "economicLossesEd";
      }
      //根据类型查询四个临界值设置
      getSingle({ type:estimateObj }).then(res => {
        if (res.code == 200) {
          if (estimateObj == '1') {
            form1.value = res.data
          } else if (estimateObj == '2') {
            form2.value = res.data
          } else {
            form3.value = res.data
          }
          //选择评估对象--获取单指标风险区划临界值
          typeChange(form.value.estimateObj);
          //区划查询
          queryForm.value = {
            assessType:assessType,
            range:rangeObj.value,//四个临界值设置;新疆、青海和西藏地区四个临界值设置
            faeId: resultEntity.value.faeId, //id
          };
        }
      });
    }
  })
}

// 选择影响场数据
const influenceFieldOpen = ref(false)
const chooseInfluenceField = () => {
  influenceFieldOpen.value = true
}
//影响场数据
const getInfluence = val => {
  form.value.condition = val
}
//选择地震输入方式
const modeChange = (val)=>{
  form.value.condition = "";
  let conditionType = "11";
  //seismicInputMode: "0",//地震输入方式 0、烈度；1、4个概率水准；2、地震影响场
  if(val=="0"){
    conditionType = "11";
  }else if(val=="1"){
    conditionType = "21";
  }else if(val=="2"){
    conditionType = "31";
  }
  form.value.conditionType = conditionType;//11:烈度;21:4个概率水准(ld);22:4个概率水准(pga);31:地震影响场
}

onMounted(() => {
  initOpen();
  getData('1');
  getData('2');
  getData('3');
})

</script>

<style scoped lang="scss">
.new-queryDiv {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 600px;
  background: rgba(255,255,255,0.8);
  border: 1px solid gray;
  padding: 20px;
}
</style>